
package com.goldsand.collaboration.handoff.common.connection;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.goldsand.collaboration.handoff.R;

import org.apache.http.conn.util.InetAddressUtils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class Utils {
    private static final String APP_TYPE_CONFIG = "app_config_type";
    private static final String CONFIG_PREFERENCE_NAME = "appp_config";
    private static final String APP_TYPE_SERVER = "server";

    public static boolean isCurrentAppTypeServer(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(CONFIG_PREFERENCE_NAME,
                Context.MODE_PRIVATE);
        String type = preferences.getString(APP_TYPE_CONFIG,
                context.getString(R.string.app_config_type));
        return APP_TYPE_SERVER.equals(type);
    }

    /**
     * Get local wifi ip address
     * @return
     * @throws SocketException
     */
    public static String getLocalHostIp() throws SocketException {
        String ipaddress = "";
        Enumeration<NetworkInterface> en = NetworkInterface
                .getNetworkInterfaces();
        while (en.hasMoreElements()) {
            NetworkInterface nif = en.nextElement();
            Enumeration<InetAddress> inet = nif.getInetAddresses();
            while (inet.hasMoreElements())
            {
                InetAddress ip = inet.nextElement();
                if (!ip.isLoopbackAddress()
                        && InetAddressUtils.isIPv4Address(ip
                                .getHostAddress())) {
                    return ip.getHostAddress();
                }
            }
        }
        return ipaddress;
    }

    /**
     * Get the wifi connected status.
     * @param context
     * @return
     */
    public static boolean getWifiConnectedStatus(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return wifiInfo.isConnected();
    }
}
